package com.lily.aidouzixun.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.activity.DynamicDetailActivity;
import com.lily.aidouzixun.activity.LoginActivity;
import com.lily.aidouzixun.activity.PublishDynamicActivity;
import com.lily.aidouzixun.adapter.MyListAdapter;
import com.lily.aidouzixun.adapter.MyViewHolder;
import com.lily.aidouzixun.bean.DynamicHomeInfo;
import com.lily.aidouzixun.bean.DynamicInfo;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.PullToRefreshView;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.MySharedPreferences;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 动态Fragment
 */
public class DynamicFragment extends Fragment{
    private static final String TAG = "DynamicFragment";

    private TitleBar mTitleBar;
    private PopupWindow popupWindow;
    private PullToRefreshView pullToRefreshView;
    private ScrollView sv;
    private ListView lvDiscuss;
    private ProgressDialog mProgressDialog;

    private static String key; //key,一般为hascode,作为Map中的key值
    private static Context mContext;
    private Activity mActivity;
    private static final String TITLE = "动态";
    private static MyHandler mHandler; //自定义的Handler，用于发送和接收消息
    private boolean isRefreshing = false;    //是否正在刷新
    private MyListAdapter mListAdapter;
    private List<DynamicInfo> discussList;
    private int action;	//用户行为，1-得到新数据;2-得到更多数据
    private int curPageNum;
    private int totalPageNum;
    public static int discussCategory;    //动态类别 1-全部；2-我的

    /**
     * 操作类型
     */
    public interface ActionType {
        /**
         * 加1-点赞，收藏
         */
        int UP = 1;
        /**
         * 减1-取消点赞，取消收藏
         */
        int DOWN = -1;
    }

    public interface DiscussCategory {
        /**
         * 所有
         */
        int All_DISCUSS = 1;
        /**
         * 我的
         */
        int MY_DISCUSS = 2;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(); //初始化
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        L.i(TAG, "onCreateView");
        if(container == null) return null;
        View view = inflater.inflate(R.layout.discuss_fragment, container, false);
        findViews(view);
        setListeners();
        return view;
    }

    /**
     * 初始化方法
     */
    private void init() {
        action = 1;
        discussCategory = DiscussCategory.All_DISCUSS;
        key = "" + this.hashCode();
        mContext = getActivity();
        mActivity = getActivity();
        mHandler = new MyHandler(DynamicFragment.this);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mActivity);
        MyConfig.getInstance(mContext).registerHandler(this.hashCode(), mHandler);
        mListAdapter = new MyListAdapter(LayoutInflater.from(mContext), MyViewHolder.HolderType.DISCUSS, mContext);
        //清除Glide缓存
        Glide.get(mContext).clearMemory();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(mContext).clearDiskCache();
            }
        }).start();
        getDiscussData(1);   //得到动态的信息

    }
    /**
     * 得到控件
     * @param view
     */
    private void findViews(View view) {
        mTitleBar = (TitleBar) view.findViewById(R.id.mytitlebar);
        mTitleBar.setTitle("动态");
        mTitleBar.setLeftOperationVisible(false);
        //mTitleBar.showThirdTitle(true);
        pullToRefreshView = (PullToRefreshView) view.findViewById(R.id.refreshable_view);
        pullToRefreshView.setNeedGetMoreData(true);
        pullToRefreshView.setNeedGetNewData(true);
        pullToRefreshView.setFootMode(PullToRefreshView.FootViewMode.ClickAble);
        pullToRefreshView.setOnRefreshListener(refreshListener);
        sv = (ScrollView) view.findViewById(R.id.sv);
        ImageView ivAdd = new ImageView(mContext);  //设置右边的图标
        ivAdd.setBackgroundResource(R.drawable.bg_add_blue);
        mTitleBar.setRightOperation(ivAdd);
        lvDiscuss = (ListView) view.findViewById(R.id.lv_discuss);
        lvDiscuss.setAdapter(mListAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        //getDiscussData(1);   //得到动态的信息
    }


    /**
     * 跳转到登录界面
     */
    public void gotoLoginActivity() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra(MyConstant.IntentKey.BACK_TITLE, TITLE);
        startActivityForResult(intent, MyConstant.IntentForResultCODE.LOGIN_REQUESTCODE);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //右边的图片
        mTitleBar.setRightImageClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyConfig.isLogined(mContext)) {
                    Intent intent = new Intent(mContext, PublishDynamicActivity.class);
                    intent.putExtra(MyConstant.IntentKey.BACK_TITLE, TITLE);
                    startActivityForResult(intent, MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_REQUESTCODE);
                } else {
                    T.shortToast(mContext, "请先登录！");
                    gotoLoginActivity();
                }
                //T.shortToast(mContext, "发表动态的功能，暂未实现！");
            }
        });
        //动态Item监听
        lvDiscuss.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                DynamicInfo discussInfo = discussList.get(i);
                if (discussInfo != null) {
                    Intent discussDetailIntent = new Intent(mContext, DynamicDetailActivity.class);
                    discussDetailIntent.putExtra(MyConstant.IntentKey.BACK_TITLE, TITLE);
                    discussDetailIntent.putExtra(MyConstant.IntentKey.DISCUSSINFO, discussInfo);
                    startActivity(discussDetailIntent);
                }
            }
        });
        /*mTitleBar.setTitleListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTitleBar.getThirdTitle().setSelected(true);
                showPopupWindow(view);
            }
        });*/
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.e(TAG, "onHiddenChanged: " + hidden);
        if (!hidden && MySharedPreferences.getInstance().getNeedRefreshDynamic(mContext)) {
            getDiscussData(1);
            MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, false);
        }
    }

    /**
     * 显示悬浮框
     * @param view
     */
    private void showPopupWindow(View view) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.discuss_pop_window, null);
        TextView tvAllDiscuss = (TextView) contentView.findViewById(R.id.tv_all_discuss);
        TextView tvMyDiscuss = (TextView) contentView.findViewById(R.id.tv_my_discuss);
        if (discussCategory == DiscussCategory.All_DISCUSS) {
            tvAllDiscuss.setSelected(true);
            tvMyDiscuss.setSelected(false);
        } else if (discussCategory == DiscussCategory.MY_DISCUSS){
            tvMyDiscuss.setSelected(true);
            tvAllDiscuss.setSelected(false);
        }
        tvAllDiscuss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                discussCategory = DiscussCategory.All_DISCUSS;
                getDiscussData(1);
                popupWindow.dismiss();
            }
        });
        tvMyDiscuss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                discussCategory = DiscussCategory.MY_DISCUSS;
                getDiscussData(1);
                popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                mTitleBar.getThirdTitle().setSelected(false);
                return false;
            }
        });
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_halfbalck_solid));
        popupWindow.showAsDropDown(view, 0, 40);

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_REQUESTCODE:
                if (data != null) {
                    int tag = data.getIntExtra(MyConstant.IntentKey.TAG, -1);
                    if (tag == 0) {
                        getDiscussData(1);   //发布成功，则重新得到列表信息
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 从服务端得到动态信息
     */
    private void getDiscussData(int pager) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.DISCUSS_HOME);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.DISCUSS_HOME);
        param.put(MyConstant.RequireParams.CATEGORY, discussCategory);
        param.put(MyConstant.RequireParams.PAGE, pager);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 点赞
     * @param did
     * @param actionType 操作类型：1：点赞；-1：取消点赞
     */
    public static void support(String did, int actionType) {
        MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, true);
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.SUPPORT_DISCUSS);
        param.put(MyConstant.RequireParams.MAP_KEY, key + MyConstant.DataType.SUPPORT_DISCUSS);
        param.put(MyConstant.RequireParams.DID, did);
        param.put(MyConstant.RequireParams.ACTION, actionType);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 收藏
     * @param did
     * @param actionType 操作类型：1：收藏；-1：取消收藏
     */
    public static void collect(String did, int actionType) {
        MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, true);
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.COLLECT_DISCUSS);
        param.put(MyConstant.RequireParams.MAP_KEY, key + MyConstant.DataType.COLLECT_DISCUSS);
        param.put(MyConstant.RequireParams.DID, did);
        param.put(MyConstant.RequireParams.ACTION, actionType);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 显示动态首页内容
     * @param discussHomeInfo
     */
    private void showContent(DynamicHomeInfo discussHomeInfo) {
        switch (discussCategory) {
            case DiscussCategory.All_DISCUSS:
                mTitleBar.setTitle("动态");
                break;
            case DiscussCategory.MY_DISCUSS:
                mTitleBar.setTitle("我的");
                break;
            default:
                break;
        }
        if (discussHomeInfo == null) {
            mListAdapter.setData(null);
            mListAdapter.notifyDataSetChanged();
            pullToRefreshView.onHeaderRefreshComplete();
            pullToRefreshView.onComplete(false);
            return;
        }
        curPageNum = discussHomeInfo.getCurpage();
        totalPageNum = discussHomeInfo.getTotalpage();
        if (discussList == null || action == 1) {
            discussList = new ArrayList<DynamicInfo>();
        }
        for (int i =0; i<discussHomeInfo.getDiscussList().size(); i++) {
            discussList.add(discussHomeInfo.getDiscussList().get(i));
        }
        if (action == 1) {
            sv.smoothScrollTo(0,0);
            lvDiscuss.setFocusable(false);
        }
        mListAdapter.setData(discussList);
        mListAdapter.notifyDataSetChanged();
        pullToRefreshView.onHeaderRefreshComplete();
        pullToRefreshView.onComplete(false);
    }

    public static MyHandler getMyHandler() {
        return mHandler;
    }

    /**
     * 删除动态
     * @param did
     */
    private void deleteDiscuss(String did) {
        MySharedPreferences.getInstance().setNeedRefreshDynamic(mContext, true);
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.DELETE_DISCUSS);
        param.put(MyConstant.RequireParams.MAP_KEY, key + MyConstant.DataType.DELETE_DISCUSS);
        param.put(MyConstant.RequireParams.DID, did);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Fragment>  mFragmentReference;

        /**
         * 构造方法，传递fragment对象，防止内存泄露
         * @param fragment
         */
        MyHandler(Fragment fragment) {
            mFragmentReference = new WeakReference<Fragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final DynamicFragment fragment = (DynamicFragment) mFragmentReference.get();
                if(fragment !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:
                            if (fragment.mProgressDialog != null) {
                                if (msg.arg1 == MyConstant.DataType.DISCUSS_HOME) {
                                }
                                fragment.mProgressDialog.setMessage("正在获取数据...");
                                fragment.mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:
                            if (fragment.mProgressDialog != null) {
                                fragment.mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED:
                            if (msg.arg1 == MyConstant.DataType.DISCUSS_HOME) { //动态首页
                                SparseArray<Object> discussHomeResult = (SparseArray<Object>) msg.obj;
                                if (discussHomeResult != null) {
                                    String errno = (String) discussHomeResult.get(0);
                                    if ("0".equals(errno)) {
                                        DynamicHomeInfo discussHomeInfo = (DynamicHomeInfo) discussHomeResult.get(2);
                                        if (discussHomeInfo != null) {
                                            fragment.showContent(discussHomeInfo);
                                        }
                                    } else {
                                        T.shortToast(fragment.mActivity, "没有数据！");
                                        fragment.showContent(null);
                                    }
                                }
                            } else if (msg.arg1 == MyConstant.DataType.SUPPORT_DISCUSS) {   //点赞
                                SparseArray<Object> supportResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) supportResult.get(0);
                                if ("0".equals(errno)) {    //点赞成功
                                    //fragment.getDiscussData(1);
                                }
                            } else if (msg.arg1 == MyConstant.DataType.COLLECT_DISCUSS) {   //收藏
                                SparseArray<Object> collectResult = (SparseArray<Object>) msg.obj;
                                String errno = (String) collectResult.get(0);
                                if ("0".equals(errno)) {    //收藏成功
                                    //fragment.getDiscussData(1);
                                }
                            } else if (msg.arg1 == MyConstant.DataType.DELETE_DISCUSS) {    //删除
                                SparseArray<Object> deleteDiscussResult = (SparseArray<Object>) msg.obj;
                                if (deleteDiscussResult != null) {
                                    String errno = (String) deleteDiscussResult.get(0);
                                    if ("0".equals(errno)) {
                                        fragment.getDiscussData(1);
                                    } else {
                                        T.shortToast(fragment.mActivity, "删除失败！");
                                    }
                                }
                            }
                            break;
                        case MessageType.DELETE_DISCUSS:   //删除动态
                            String did = (String) msg.obj;
                            fragment.deleteDiscuss(did);
                            break;
                        case MessageType.GOTO_LOGIN:   //跳转登录界面
                            fragment.gotoLoginActivity();
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
    PullToRefreshView.OnRefreshListener refreshListener = new PullToRefreshView.OnRefreshListener() {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub
            action = 1;
            getDiscussData(1);
        }

        @Override
        public boolean onMore(int nextPageNum) {
            // TODO Auto-generated method stub
            action = 2;
            if(curPageNum < totalPageNum) {
                getDiscussData(curPageNum + 1);
                return true;
            } else {
                pullToRefreshView.onComplete(false);
                return false;
            }
        }

        @Override
        public void onGetPageData() {
            // TODO Auto-generated method stub
        }

    };
}
